package com.zxy.hotel.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zxy.hotel.entity.RS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletOutputStream;

/**
 * @author 14995
 * @description
 * @create 2021-12-12 下午 9:18
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //使用了JWT，不需要csrf
        http.csrf().disable()
                //基于token，不需要session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                //禁用缓存
                .headers()
                .cacheControl().disable();

        //jwt登录拦截器
        http.addFilterBefore(new JwtAuthFilter(userDetailsService), UsernamePasswordAuthenticationFilter.class)
                //异常处理 自定义未授权和未登录结果返回
                .exceptionHandling()
                .accessDeniedHandler(((request, response, accessDeniedException) -> {
                    ServletOutputStream outputStream = response.getOutputStream();
                    RS rs = RS.fail().setCode(-43).message("未授权");
                    ObjectMapper objectMapper = new ObjectMapper();
                    byte[] bytes = objectMapper.writeValueAsBytes(rs);
                    outputStream.write(bytes);
                    outputStream.flush();
                    outputStream.close();
                }))
                .authenticationEntryPoint(((request, response, accessDeniedException) -> {
                    ServletOutputStream outputStream = response.getOutputStream();
                    RS rs = RS.fail().setCode(-41).message("未登录");
                    ObjectMapper objectMapper = new ObjectMapper();
                    byte[] bytes = objectMapper.writeValueAsBytes(rs);
                    outputStream.write(bytes);
                    outputStream.flush();
                    outputStream.close();
                }));
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/admin/login",
                "/css/**",
                "/fonts/**",
                "/img/**",
                "/js/**",
                "/favicon.ico",
                "/index.html",
                "/"
        );
    }
}
